var lun = {
	init : function() {
		lun.bindEvent();
		lun.initTree();
	},
	/**
	 * 获取下拉列表框被选中的值
	 * @returns {___anonymous_poolName}
	 */
	select : function(){
		var name=document.getElementById("poolName");
		for(var i=0;i<name.length;i++){
			if(name[i].selected==true){
				poolName=name[i].innerHTML;
				return poolName;
			}
		}
	},
	lunMigrate : function(id){
		var destImage = $("#lunName").val();
		var destPool = lun.select();
		data = {
			destPool : destPool,
			destImage : destImage
		};
		$.ajax({
			type : "post",
			data : data,
			url : baseURL + "/cluster/lun/" + id,
			success : function(result) {
				if (result.result != 'success') {
					common.showTip({
						text : "迁移失败",
						success : false
					});
				} else {
					common.showTip({
						text : "操作成功！",
						success : true,
						autoclose : false,
						callback : function() {
							lun.initTree();
						}
					});
				}
			}
		});
	},
	bindEvent : function() {
		/**
		 * 添加
		 */
		$('#add').unbind('click').bind('click', function() {
			lun.edit();
		});
		/**
		 * 保存
		 */
		$('#save').unbind('click').bind('click', function() {
			lun.save();
		});
		//删除
		$('#del').unbind('click').bind('click', function() {
			var id = $('#editinfo').find('input[name="id"]').val();
			common.confirmDialog('确认删除？',function() {
				lun.batchDel(id, false);
			});
		});
		//强制删除
		$('#forceDel').unbind('click').bind('click', function() {
			var id = $('#editinfo').find('input[name="id"]').val();
			common.confirmDialog('确认删除？',function() {
				lun.batchDel(id, true);
			});
		});
		/**
		 * 清楚
		 */
		$('#cancel').unbind('click').bind('click', function() {
			var id = $('#editinfo').find('input[name="id"]').val();
			if(id == null || id == "") {
				lun.changeType(0);
				$('#type').find('p').html('')
				$('#editinfo').find('input[type="text"]').val("");
				$('#editinfo').find('input[type="hidden"]').val("");
			} else {
				$('#editinfo').find('input[type="text"]').val("");
				$('#editinfo').find('input[type="hidden"]').not("input[name='id']").not("input[name='parentId']").val("");
			}
		});
		/**
		 * 选择父
		 */
		$('#parent').unbind('click').bind('click', function() {
			var poolName = $('#editinfo').find('select[name="poolName"]').val();
			opt = {
				url : baseURL + "/cluster/lun/tree",
				param : {type : 6, poolName : poolName, filterType : 2},
				title : "请选择",
				leftTitle : "镜像",
				rightTitle2 : "上级",
				rightText : "已选",
				cache : false,
				width : 680,
				height : 480,
				single : true, // 是否单选，默认单选
				canSelectRoot : true,
				onlyLeafSelect : false,
				confirm : function(data){
					if(data.nodes.outype == '9') {//pool
						$('#type').find('p').html('').html('卷');
						$('#type').find('input[name="type"]').val('0');
					} else if(data.nodes.outype == '0') {//卷
						$('#type').find('p').html('').html('快照');
						$('#type').find('input[name="type"]').val('1');
					} else {//快照
						$('#type').find('p').html('').html('克隆');
						$('#type').find('input[name="type"]').val('2');
					}
					lun.changeType($('#type').find('input[name="type"]').val());
					$('#parent').val(data.text);
					$('#parentId').val(data.id);
				} // 回调函数，返回选中的节点
			}
		  	common.tree(opt);
		});
		/**
		 * 同步
		 */
		$('#sync').unbind('click').bind('click', function() {
			$.ajax({
				type : "post",
				url : baseURL + "/cluster/lun/sync",
				dataType : "json",
				success : function(json){
					if(json.success) {
						common.showTip({text:"操作成功！",success:true, autoclose : false, callback : function() {
								lun.initTree();
							}
						});
					} else {
						common.showTip({text:"操作失败！",success:false});
					}
				}
			});
		});
		/**
		 * QOS
		 */
		$('#qos').unbind('click').bind('click', function() {
			var isexpand = $('#isexpand').val();
			var isreduce = $('#isreduce').val();
			if(isexpand == '1' || isreduce == '1') {
				common.confirmDialog("请先保存扩容或缩容操作！是否保存？", function() {
					lun.save();
				});
			} else {
				$('#isqos').val('1');
				var qosType = $('#qosType').find(':input').val() || 0;
				var qosRead = $('#qosRead').find('p').html().trim();
				var qosWrite = $('#qosWrite').find('p').html().trim();
				var qosTypeHtml = new Stringbuilder();
				qosTypeHtml.append('<select style="width:54%" name="qosType">');
				qosTypeHtml.append('	<option value="0">IOPS</option>');
				qosTypeHtml.append('	<option value="1">带宽</option>');
				qosTypeHtml.append('</select>');
				$('#qosType').html('').html(qosTypeHtml.toString());
				$('#qosType').find('select').val(qosType);
				var qosReadHtml = new Stringbuilder();
				qosReadHtml.append('<input type="text" name="qosRead" value=""/>');
				$('#qosRead').html('').html(qosReadHtml.toString());
				$('#qosRead').find('input').val(qosRead);
				var qosWriteHtml = new Stringbuilder();
				qosWriteHtml.append('<input type="text" name="qosWrite" value=""/>');
				$('#qosWrite').html('').html(qosWriteHtml.toString());
				$('#qosWrite').find('input').val(qosWrite);
				$('#buttonDiv').show();
			}
		});
		/**
		 * 扩容
		 */
		$('#expand').unbind('click').bind('click', function() {
			var isqos = $('#isqos').val();
			if(isqos == '1') {
				common.confirmDialog("请先保存QOS操作！是否保存？", function() {
					lun.save();
				});
			} else {
				$('#isexpand').val('1');
				$('#isreduce').val('0');
				var size = $('#oldSize').val() || $('#size').find('input').val();
				var sizeHtml = new Stringbuilder();
				sizeHtml.append('<input type="text" name="size" value=""/>(MB)');
				$('#size').html('').html(sizeHtml.toString());
				$('#size').find('input').val(size);
				$('#buttonDiv').show();
			}
		});
		/**
		 * 缩容
		 */
		$('#reduce').unbind('click').bind('click', function() {
			common.confirmDialog('危险操作，请确认？',function() {
				var isqos = $('#isqos').val();
				if(isqos == '1') {
					common.confirmDialog("请先保存QOS操作！是否保存？", function() {
						lun.save();
					});
				} else {
					$('#isreduce').val('1');
					$('#isexpand').val('0');
					var size = $('#oldSize').val() || $('#size').find('input').val();
					var sizeHtml = new Stringbuilder();
					sizeHtml.append('<input type="text" name="size" value=""/>(MB)');
					$('#size').html('').html(sizeHtml.toString());
					$('#size').find('input').val(size);
					$('#buttonDiv').show();
				}
			});
		});
		/**
		 * acl列表
		 */
		$('#aclList').unbind('click').bind('click', function() {
			lun.showMappedHosts('mappingHostsByLun');
		});
		/**
		 * acl控制
		 */
		$('#aclControl').unbind('click').bind('click', function() {
			lun.showMappedHosts('mappedHostByLun');
		});
		/**
		 * 卷迁移
		 */
		$("#migrate").unbind('click').bind('click', function() {
			var selectId = $("#parentId").val();
			var poolName = $("#pool").val();
			if (selectId == "") {
				selectId = $("#editinfo").find($("input[name='id']")).val();
			}
			var lunId = {lunId : selectId}
			var lunName;
			$.ajax({
				type : "POST",
				data : lunId,
				url : baseURL + "/cluster/lun/getParentById",
				success : function(result) {
					if (result.result == 'success') {
						lunName = result.Lun.name;
						var param = {lunName : lunName,poolName : poolName};
						common.dialog({
							obj : "#migrateForm",
							param : param,
							type : "POST",
							url : baseURL + "/cluster/lun/migrate",
							title : localeMsg.common.prompt,
							width : 400,
							confirm : function() {
								if ($("#migrateForm").form('validate') != true) {
									return;
								}
								lun.lunMigrate(selectId);
							}
						});
					} else {
						common.showTip({
							text : "此卷含有快照无法迁移！",
							success : false
						});
					}
				}
			});
			
		});
		
		/**
		 * 查询
		 */
		$('#search').unbind('click').bind('click', function() {
			var param = {};
			param.poolName = $('#serachPoolName').val();
			param.lunType = $('#serachType').val();
			lun.initTree(param);
		});
		/**
		 * 回滚快照
		 */
		$('#rollback').unbind('click').bind('click', function() {
			var lunType = $('#type').find('input[name="type"]').val();
			var poolName = $('#pool').val();
			if(lunType == '0') {//卷
				var parentId = $('#editinfo').find('input[name="id"]').val();
				opt = {
					url : baseURL + "/cluster/lun/tree",
					param : {type : 6, poolName : poolName, lunType : 1, parentId : parentId},
					title : "请选择",
					leftTitle : "快照",
					rightTitle2 : "pool",
					rightText : "已选",
					cache : false,
					width : 680,
					height : 480,
					single : true, // 是否单选，默认单选
					onlyLeafSelect : true,
					confirm : function(data){
						lun.snapRollback(data.id);
					} // 回调函数，返回选中的节点
				}
			  	common.tree(opt);
			} else {//快照
				var id = $('#editinfo').find('input[name="id"]').val();
				lun.snapRollback(id);
			}
		});
		/**
		 * 保护快照
		 */
		$('#protect').unbind('click').bind('click', function() {
			var param = {};
			param.isProtect = true;
			param.id = $('#editinfo').find('input[name="id"]').val();
			lun.snapProtect(param);
		});
		/**
		 * 解除快照保护
		 */
		$('#unprotect').unbind('click').bind('click', function() {
			var param = {};
			param.isProtect = false;
			param.id = $('#editinfo').find('input[name="id"]').val();
			lun.snapProtect(param);
		});
		/**
		 * 填充克隆
		 */
		$('#flatten').unbind('click').bind('click', function() {
			var id = $('#editinfo').find('input[name="id"]').val();
			$.ajax({
				type : "get",
				url : baseURL + "/cluster/lun/clone/flatten",
				data : {id : id},
				dataType : "json",
				success : function(json){
					if(json.success) {
						common.showTip({text:"操作成功！",success:true, autoclose : false, callback : function() {
								lun.initTree();
							}
						});
					} else {
						common.showTip({text:"操作失败！",success:false});
					}
				}
			});
		});
		/**
		 * 删除卷下快照
		 */
		$('#delSnap').unbind('click').bind('click', function() {
			var id = $('#editinfo').find('input[name="id"]').val();
			common.confirmDialog('确认删除？',function() {
				$.ajax({
					type : "get",
					url : baseURL + "/cluster/lun/snap/delAll",
					data : {id : id},
					dataType : "json",
					success : function(json){
						if(json.success) {
							common.showTip({text:"操作成功！",success:true, autoclose : false, callback : function() {
									lun.initTree();
								}
							});
						} else {
							common.showTip({text:"操作失败！" + json.message,success:false});
						}
					}
				});
			});
		});
	},
	/**
	 * 初始化镜像树
	 */
	initTree : function(param) {
		var param = param || {};
		$.ajax({
			type : "get",
			url : baseURL + "/cluster/lun/tree",
			data : param,
			dataType : "json",
			success : function(json){
				$('#tree').tree({
	//				url: baseURL + "/cluster/lun/tree",
					data : json,
					checkbox: false,
					animate : true,
					cascadeCheck : false,
					// 单击展开
					onClick : function(node){
						$(this).tree("expand", node.target);
						var id=node.id;
						if(node.outype != 9) {
							$('#parentId').val(id);
							$('#parentId').attr('data', node.text);
							$('#pool').val(node.topId);
							lun.edit(id);
						} else {
							$('#pool').val(id);
							$('#parentId').val('');
							$('#parentId').attr('data', '');
							$("#info").ajaxpager({
								target: "#info",
								callback: function() {
									lun.showByPager(node.text);
								}
							});
						}
					},
					onCheck:function(node, checked){
						/*var attr = {
								code: node.attributes.ext1 || node.attributes.code,
								codes: node.attributes.ext1 || node.attributes.codes,
								localeName: node.attributes.locale || node.attributes.localeName,
								localeNames: node.attributes.locale || node.attributes.localeNames,
								zhnames: node.attributes.name || node.attributes.zhnames,
								ennames: node.attributes.nameEn || node.attributes.ennames,
								externalCode: node.attributes.externalCode
						};
						// 更新选中节点属性
						$("#easytree" + t).tree("update", {
							target: node.target,
							attributes: addCheckPath("#easytree" + t, node.target, attr, o.pathSpliter)
						});*/
					},
					onLoadSuccess: function(node, data) {
						//设置纵向滚动条，IE8会不能出现滚动条
						/*$("#easytree" + t).parent().css({'overflow-y':'scroll'});
						//远程检索
						var searchUrl = url.replace('/dic/tree', '/dic/tree/search');
						var opt = {
								callback:function(data){
									var $tree = $("#easytree" + t);
									var node = $tree.tree('find', data.id);
									$tree.tree('select', node.target);
									$tree.tree('expandTo', node.target);
						}};
						autocompleteRemortDicTree($('#treediv' + t).find(":input[name=keyword]"), searchUrl, opt);*/
					}
				});
				//清空详情页面
				//$('#info').html('');
			}
		});
	},
	/**
	 * 编辑
	 * @param {} id
	 */
	edit : function(id) {
		var poolName = $('#pool').val();
		var parentId = $('#parentId').val();
		$.ajax({
            type : "post",
            url : baseURL + "/cluster/lun/edit",
            data : {id : id, poolName : poolName, parentId : parentId},
            dataType : "html",
            success : function(resultHtml) {
                $("#info").empty();
                $("#info").html(resultHtml);
                if(id == null) {
	                var parentType = $('#type').find('input[name="type"]').val();
	                if(parentType == '0') {//卷
						$('#type').find('p').html('').html('快照');
						$('#type').find('input[name="type"]').val('1');
					} else if(parentType == '1') {//快照
						$('#type').find('p').html('').html('克隆');
						$('#type').find('input[name="type"]').val('2');
					}
	                var type = $('#type').find('input[name="type"]').val();
	                lun.changeType(type);
                }
            }
        });
	},
	/**
	 * 更改镜像类型
	 * @param {} type
	 */
	changeType : function(type) {
		if(type == "0") {
			$('#size').show();
			$('#objectSize').show();
		} else if(type == '1') {
			$('#objectSize').hide();
			$('#size').hide();
		} else if(type == '2') {
			$('#objectSize').show();
			$('#size').hide();
		}
	},
	/**
	 * 保存
	 */
	save : function() {
		var isqos = $('#isqos').val();
		var isexpand = $('#isexpand').val();
		var isreduce = $('#isreduce').val();
		var isMapping = $('#isMapping').val();
		var url = '/cluster/lun/save';
		if(isqos == '1') {
			url = '/cluster/lun/qos';
		}
		if(isexpand == '1' || isreduce == '1') {
			url = '/cluster/lun/updateSize';
		}
		var options ={
            url : baseURL + url,   
            type : 'post',                    
            data : {isqos : isqos, isexpand : isexpand, isreduce : isreduce},
            beforeSubmit : function() {
            	if(isqos=='1'){
	            	//选择了iops操作
	            	if($('#qosType').find('select').val()==0){
	            		//获取输入的读写值
	            		var qosReadValue = $('#qosRead').find('input').val();
	            		var qosWriteValue = $('#qosWrite').find('input').val();
            			if(1000000000>parseInt(qosReadValue)&&parseInt(qosReadValue)>11&&1000000000>parseInt(qosWriteValue)&&parseInt(qosWriteValue)>11){
            			}else{
            				common.showTip({text:localeMsg.lun.iopsRange,success:false, callback : function() {
            					$('#qosRead').find('input').val(qosReadValue);
            				}
            				});
            				return false;	
            			}
	            	}else{//选择了带宽操作
	            		var qosReadValue = $('#qosRead').find('input').val();
	            		var qosWriteValue = $('#qosWrite').find('input').val();
            			if(1000000000>parseInt(qosReadValue)&&parseInt(qosReadValue)>11&&1000000000>parseInt(qosWriteValue)&&parseInt(qosWriteValue)>11){
            			}else{
            				common.showTip({text:localeMsg.lun.bandWidthRange,success:false, callback : function() {
            					$('#qosRead').find('input').val(qosReadValue);
            				}
            				});
            				return false;	
            			}
	            	}
            	}
            	if(isexpand == '1') {
            		var oldSize = $('#oldSize').val();
            		var size = $('#editinfo').find('input[name="size"]').val();
            		if(parseInt(oldSize) > parseInt(size)) {
            			common.showTip({text:"扩容后大小不能小于原大小！",success:false, callback : function() {
            					$('#editinfo').find('input[name="size"]').val(oldSize);
            				}
            			});
            			return false;
            		}
            	}
            	if(isreduce == '1') {
            		var oldSize = $('#oldSize').val();
            		var size = $('#editinfo').find('input[name="size"]').val();
            		if(parseInt(oldSize) < parseInt(size)) {
            			common.showTip({text:"缩容后大小不能大于原大小！",success:false, callback : function() {
            					$('#editinfo').find('input[name="size"]').val(oldSize);
            				}
            			});
            			return false;
            		}
            	}
            },
			success : function(data){
				if(data.success) {
					var id = data.lun.id;
					common.showTip({text:"操作成功！",success:true, autoclose : false, callback : function() {
							//按钮重置
							$('#isqos').val('0');
							$('#isexpand').val('0');
							$('#isreduce').val('0');
							lun.initTree();
							lun.edit(id);
						}
					});
				} else {
					common.showTip({text:"操作失败！" + data.message,success:false, autoclose : false});
				}
            }   
		};
		if(isMapping == '1' && (isexpand == '1' || isreduce == '1')) {
			common.confirmDialog("此卷已映射需要执行脚本！", function() {
				$('#editinfo').ajaxSubmit(options);
			}, null, function() {
				$('#isqos').val('0');
				$('#isexpand').val('0');
				$('#isreduce').val('0');
			});
		} else {
			$('#editinfo').ajaxSubmit(options);
		}
	},
	/**
	 * 批量删除
	 * @param {} ids
	 * @param {} force
	 */
	batchDel : function(ids, force) {
		var force = force || false;
		$.ajax({
			type:"post",
			url: baseURL + "/cluster/lun/batchDel",
			data: {ids : ids, force : force},
			dataType:"json" ,
			success :function(data){
				if(data){
					if(data.success){
						common.showTip({text:"操作成功！",success:true});
						$('#parentId').val('');
						$('#parentId').attr('data', '');
						lun.initTree();
					}else{
						common.showTip({text:"操作失败！" + data.message,success:false});
					}
				}
		   }
		});
	},
	/**
	 * 保存lun-host关系
	 * @param {} lunId
	 * @param {} hostArr
	 * @param {} type
	 */
	saveLunHosts : function(lunId, hostArr,type) {
		$.ajax({
			type : "post",
			url : baseURL + "/mapping/saveLunHosts",
			traditional: true,
			data : {lunId: lunId, hostIds : hostArr,type :type},
			dataType : "json",
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess,
						success: true
					});
				}else if(json.result && json.result == "wrong"){
					var names = "";
					for(var i=0; i<json.hostNames.length; i++)  
                       {  
                        names+= json.hostNames[i]+",";
                       }  
					names = names.substr(0,names.length - 1);
					common.showTip({
						title : localeMsg.common.warn,
						//text : "移除后"+names+"将不能与"+json.hostGroupNames+"映射",
						text : localeMsg.host.ifRemove+names+localeMsg.host.willNot+json.hostGroupNames+localeMsg.host.mapping,
						success: false
					});
				}else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
			}
		});
	},
	/**
	 * 显示lun映射的hosts
	 */
	/*showMappedHosts :function(type){
		var confirmText = localeMsg.common.confirm
		var title = localeMsg.host.list;
		var param = {};
		param.type = type;
		if (type=="mappedHostByLun") {
			confirmText = localeMsg.common.deleted;
		}
		var id = $('#editinfo').find('input[name="id"]').val();
		param.lunId = id;
		common.dialog({
			type : "get",
			url : baseURL + "/mapping/hostsList",
			param : param,
			title : title,
			width : 600,
			confirm : function(dialog) {
				var hostArr = [];
				$(dialog).find("input[name='hostId']:checked").each(function() {
					hostArr.push($(this).val());
				});
				if(!(hostArr.length>0)) {
					return;
				};
				lun.saveLunHosts(id, hostArr,type);
			},
			confirmText : confirmText
		});
	},*/
	
	showMappedHosts :function(type){
		var confirmText = localeMsg.common.confirm;
		var title = localeMsg.host.list;
		var url = baseURL + "/mapping/hostsList";
		var param = {};
		param.type = type;
		if (type=="mappedHostByLun") {
			confirmText = localeMsg.common.deleted;
		}
		var id = $('#editinfo').find('input[name="id"]').val();
		param.lunId = id;
		var dialog;
		if ($("#mappedLunList").length < 1) {
			$("#listMappedLunForm").append('<div id="mappedLunList" ></div>');
			dialog = "#mappedLunList";
		};
		common.dialog({
			obj : dialog,
			title : localeMsg.host.list,
			width : 680,
			height : 540,
			confirm : function(dialog) {
				var hostArr = [];
				$(dialog).find("input[name='hostId']:checked").each(function() {
					hostArr.push($(this).val());
				});
				if(!(hostArr.length>0)) {
					return;
				};
				lun.saveLunHosts(id, hostArr,type);
			},
			confirmText : confirmText,
			onOpen : function() {
				$("#listMappedLunForm").ajaxpager({
					target: "#mappedLunList",
					callback: function() {
						lun.showMappedLunsByPager(id, type);
					}
				});
			}
		});
	},
	
	showMappedLunsByPager : function(id, type) {
		var pageNumber = $("#mappedLunList input[name='pageNumber']").val();
		var url = baseURL + "/mapping/hostsList";
		var param = {lunId : id, pageNumber : pageNumber};
		if (type) {
			param.type = type;
		}
		$.ajax({
			type : "get",
			url : url,
			data : param,
			success : function(html) {
				$("#mappedLunList").empty().html(html);
				$("#mappedLunList").dialog("resize");
				
			}
		});
	},
	snapProtect : function(param) {
		var param = param || {};
		$.ajax({
			type : "get",
			url : baseURL + "/cluster/lun/snap/protect",
			data : param,
			dataType : "json",
			success : function(json){
				if(json.success) {
					common.showTip({text:"操作成功！",success:true, autoclose : false, callback : function() {
							lun.initTree();
						}
					});
				} else {
					common.showTip({text:"操作失败！" + json.message,success:false});
				}
			}
		});
	},
	snapRollback : function(id) {
		$.ajax({
			type : "get",
			url : baseURL + "/cluster/lun/snap/rollback",
			data : {id : id},
			dataType : "json",
			success : function(json){
				if(json.success) {
					common.showTip({text:"操作成功！",success:true, autoclose : false, callback : function() {
							lun.initTree();
						}
					});
				} else {
					common.showTip({text:"操作失败！",success:false});
				}
			}
		});
	},
	/**
	 * validate Form
	 */
	validate:function(){
		
		$("#lunName").validatebox({
			required : true,
			validType :	['uniquename']
		});
		
	},
	/**
	 * 分页展示存储池下的所有卷列表
	 */
	showByPager : function(poolName) {
		var pageNumber = $("input[name='pageNumber']").val();
		var param = {poolName : poolName, pageNumber : pageNumber};
		$.ajax({
			type:"GET",
			data: param,
			url: baseURL+"/cluster/lun/poolInfo",
			success:function(result){
				$("#info").empty().html(result);
			}
		});
	}
}
$.extend($.fn.validatebox.defaults.rules, {
	uniquename: {
    	  validator: function(value){
    		  	var destImage=$("#lunName").val();
    			var destPool=lun.select();
    		    param={destPool:destPool,destImage:destImage}
    		    var information=true;
    			$.ajax({
    				type:"GET",
    				data:param,
    				url:baseURL+"/cluster/lun/lunNameRepeat",
    				async:false,
    				success:function(result){
    					if(result.result=="success"){
    						if(result.value=='failure'){
    							information=false;
    						}
    					}
    				}
    			});
    			return information;
          },
          message:localeMsg.verification.imagename
    }
	
});